$(document).ready(function () {

    todoList();
    discussionWidget();

    myPlot = createPlot();

    openSocket();


    /* ---------- Datable ---------- */
    $('.datatable').dataTable({
        "sDom": "<'row'<'col-lg-6'l><'col-lg-6'f>r>t<'row'<'col-lg-12'i><'col-lg-12 center'p>>",
        "bPaginate": false,
        "bFilter": false,
        "bLengthChange": false,
        "bInfo": false,
    });

    $('.countries').dataTable({
        "sDom": "<'row'<'col-lg-6'l><'col-lg-6'f>r>t<'row'<'col-lg-12'i><'col-lg-12 center'p>>",
        "bPaginate": false,
        "bFilter": false,
        "bLengthChange": false,
        "bInfo": false,
        // Disable sorting on the first column
        "aoColumnDefs": [{
            'bSortable': false,
            'aTargets': [0]
        }]
    });


    /* ---------- Map ---------- */
    $(function () {
        $('#map').vectorMap({
            map: 'world_mill_en',
            series: {
                regions: [{
                    values: gdpData,
                    scale: ['#000', '#000'],
                    normalizeFunction: 'polynomial'
                }]
            },
            backgroundColor: '#fff',
            onLabelShow: function (e, el, code) {
                el.html(el.html() + ' (GDP - ' + gdpData[code] + ')');
            }
        });
    });


    /* ---------- Placeholder Fix for IE ---------- */
    $('input, textarea').placeholder();

    /* ---------- Auto Height texarea ---------- */
    $('textarea').autosize();

    $('#recent a:first').tab('show');
    $('#recent a').click(function (e) {
        e.preventDefault();
        $(this).tab('show');
    });

    /*------- Main Calendar -------*/
    $('#external-events div.external-event').each(function () {

        // it doesn't need to have a start or end
        var eventObject = {
            title: $.trim($(this).text()) // use the element's text as the event title
        };

        // store the Event Object in the DOM element so we can get to it later
        $(this).data('eventObject', eventObject);

        // make the event draggable using jQuery UI
        $(this).draggable({
            zIndex: 999,
            revert: true,      // will cause the event to go back to its
            revertDuration: 0  //  original position after the drag
        });

    });

    var date = new Date();
    var d = date.getDate();
    var m = date.getMonth();
    var y = date.getFullYear();

    $('.calendar').fullCalendar({
        header: {
            right: 'next',
            center: 'title',
            left: 'prev'
        },
        defaultView: 'month',
        editable: true,
        events: [
            {
                title: 'All Day Event',
                start: '2014-06-01'
            },
            {
                title: 'Long Event',
                start: '2014-06-07',
                end: '2014-06-10'
            },
            {
                id: 999,
                title: 'Repeating Event',
                start: '2014-06-09 16:00:00'
            },
            {
                id: 999,
                title: 'Repeating Event',
                start: '2014-06-16 16:00:00'
            },
            {
                title: 'Meeting',
                start: '2014-06-12 10:30:00',
                end: '2014-06-12 12:30:00'
            },
            {
                title: 'Lunch',
                start: '2014-06-12 12:00:00'
            },
            {
                title: 'Birthday Party',
                start: '2014-05-10 18:05:00'
            },
            {
                title: 'Click for Google',
                url: 'http://google.com/',
                start: '2014-06-28'
            }
        ]
    });

    /*------- Moris Chart -------*/
    Morris.Donut({
        element: 'hero-donut',
        data: [
            {label: '北京', value: 17},
            {label: '上海', value: 18},
            {label: '杭州', value: 23},
            {label: '广州', value: 12},
            {label: '深圳', value: 8},
            {label: '天津', value: 22}
        ],
        colors: ["#36A9E1", "#d1b993", "#bdea74", "#67c2ef", "#fabb3d", "#ff5454"],
        formatter: function (y) {
            return y + "%"
        }
    });


    /*------- Realtime Update Chart -------*/
    /*

     $(function () {

     // we use an inline data source in the example, usually data would
     // be fetched from a server
     var data = [], totalPoints = 300;
     var res = [];
     // function getRandomData1() {
     // 	if (data.length > 0)
     // 		data = data.slice(1);
     //
     // 	// do a random walk
     // 	while (data.length < totalPoints) {
     // 		var prev = data.length > 0 ? data[data.length - 1] : 50;
     // 		var y = prev + Math.random() * 10 - 5;
     // 		if (y < 0)
     // 			y = 0;
     // 		if (y > 100)
     // 			y = 100;
     // 		data.push(y);
     // 	}
     //
     // 	// zip the generated y values with the x values
     // 	var res = [];
     // 	for (var i = 0; i < data.length; ++i)
     // 		res.push([i, data[i]])
     //    console.log(res);
     // 	//alert(res);
     // 	return res;
     // }
     function getRandomData1() {
     if (data.length > 0)
     data = data.slice(1);

     // do a random walk
     while (data.length < totalPoints) {
     var prev = data.length > 0 ? data[data.length - 1] : 50;
     var y = prev + Math.random() * 10 - 5;
     if (y < 0)
     y = 0;
     if (y > 100)
     y = 100;
     data.push(y);
     }

     // zip the generated y values with the x values
     var res = [];
     for (var i = 0; i < data.length; ++i)
     res.push([i, 0])
     return res;
     }

     function getRandomData() {
     $.ajax({
     url: '/qjiang/v1/maintenances/connected_terminals/get',
     type: 'GET',
     datatype: 'json',
     contentType: 'application/json;charset=utf-8',
     Accept: 'application/json',
     cache: false,
     success: function (data, textStatus, jqXHR) {
     res.length = 0;
     for (var i = 0; i < data.length; ++i) {
     res.push([i, parseInt(data[i].propvalue)]);
     }
     //  res = getRandomData1();


     },
     error: function (jqXHR, textStatus, errorThrown) {
     $('#result').text(errorThrown);
     }
     });
     if (res.length < 299) {
     res = getRandomData1();
     }
     return res;
     }


     // setup control widget
     var updateInterval = 30;
     $("#updateInterval").val(updateInterval).change(function () {
     var v = $(this).val();
     if (v && !isNaN(+v)) {
     updateInterval = +v;
     if (updateInterval < 1)
     updateInterval = 1;
     if (updateInterval > 2000)
     updateInterval = 2000 * 60 * 10;
     $(this).val("" + updateInterval);
     }
     });


     if ($("#realtime-update").length) {
     var options = {
     series: {shadowSize: 1},
     lines: {fill: true, fillColor: {colors: [{opacity: 1}, {opacity: 0.1}]}},
     yaxis: {min: 0, max: 100},
     xaxis: {show: false},
     colors: ["#57889c"],
     grid: {
     tickColor: "#dddddd",
     borderWidth: 0
     },
     };
     var plot = $.plot($("#realtime-update"), [getRandomData()], options);

     function update() {
     var res = getRandomData();
     console.log(res);
     if (res.length > 299) {
     plot.setData([res]);
     // since the axes don't change, we don't need to call plot.setupGrid()
     console.log(plot);
     plot.draw();
     }
     setTimeout(update, 50);//updateInterval
     }

     update();
     }

     });
     */


    /*------- Page View Chart -------*/
    $(function () {
        var data = [{
            "xScale": "ordinal",
            "comp": [],
            "main": [{
                "className": ".main.l1",
                "data": [{"y": 15, "x": "2012-11-19T00:00:00"}, {"y": 11, "x": "2012-11-20T00:00:00"}, {
                    "y": 8,
                    "x": "2012-11-21T00:00:00"
                }, {"y": 10, "x": "2012-11-22T00:00:00"}, {"y": 1, "x": "2012-11-23T00:00:00"}, {
                    "y": 6,
                    "x": "2012-11-24T00:00:00"
                }, {"y": 8, "x": "2012-11-25T00:00:00"}]
            }, {
                "className": ".main.l2",
                "data": [{"y": 29, "x": "2012-11-19T00:00:00"}, {"y": 33, "x": "2012-11-20T00:00:00"}, {
                    "y": 13,
                    "x": "2012-11-21T00:00:00"
                }, {"y": 16, "x": "2012-11-22T00:00:00"}, {"y": 7, "x": "2012-11-23T00:00:00"}, {
                    "y": 18,
                    "x": "2012-11-24T00:00:00"
                }, {"y": 8, "x": "2012-11-25T00:00:00"}]
            }],
            "type": "line-dotted",
            "yScale": "linear"
        }, {
            "xScale": "ordinal",
            "comp": [],
            "main": [{
                "className": ".main.l1",
                "data": [{"y": 12, "x": "2012-11-19T00:00:00"}, {"y": 18, "x": "2012-11-20T00:00:00"}, {
                    "y": 8,
                    "x": "2012-11-21T00:00:00"
                }, {"y": 7, "x": "2012-11-22T00:00:00"}, {"y": 6, "x": "2012-11-23T00:00:00"}, {
                    "y": 12,
                    "x": "2012-11-24T00:00:00"
                }, {"y": 8, "x": "2012-11-25T00:00:00"}]
            }, {
                "className": ".main.l2",
                "data": [{"y": 29, "x": "2012-11-19T00:00:00"}, {"y": 33, "x": "2012-11-20T00:00:00"}, {
                    "y": 13,
                    "x": "2012-11-21T00:00:00"
                }, {"y": 16, "x": "2012-11-22T00:00:00"}, {"y": 7, "x": "2012-11-23T00:00:00"}, {
                    "y": 18,
                    "x": "2012-11-24T00:00:00"
                }, {"y": 8, "x": "2012-11-25T00:00:00"}]
            }],
            "type": "cumulative",
            "yScale": "linear"
        }, {
            "xScale": "ordinal",
            "comp": [],
            "main": [{
                "className": ".main.l1",
                "data": [{"y": 12, "x": "2012-11-19T00:00:00"}, {"y": 18, "x": "2012-11-20T00:00:00"}, {
                    "y": 8,
                    "x": "2012-11-21T00:00:00"
                }, {"y": 7, "x": "2012-11-22T00:00:00"}, {"y": 6, "x": "2012-11-23T00:00:00"}, {
                    "y": 12,
                    "x": "2012-11-24T00:00:00"
                }, {"y": 8, "x": "2012-11-25T00:00:00"}]
            }, {
                "className": ".main.l2",
                "data": [{"y": 29, "x": "2012-11-19T00:00:00"}, {"y": 33, "x": "2012-11-20T00:00:00"}, {
                    "y": 13,
                    "x": "2012-11-21T00:00:00"
                }, {"y": 16, "x": "2012-11-22T00:00:00"}, {"y": 7, "x": "2012-11-23T00:00:00"}, {
                    "y": 18,
                    "x": "2012-11-24T00:00:00"
                }, {"y": 8, "x": "2012-11-25T00:00:00"}]
            }],
            "type": "bar",
            "yScale": "linear"
        }];
        var order = [0, 1, 0, 2],
            i = 0,
            xFormat = d3.time.format('%A'),
            chart = new xChart('line-dotted', data[order[i]], '#chart', {
                axisPaddingTop: 5,
                dataFormatX: function (x) {
                    return new Date(x);
                },
                tickFormatX: function (x) {
                    return xFormat(x);
                },
                timing: 1250
            }),
            rotateTimer,
            toggles = d3.selectAll('.multi button'),
            t = 3500;

        function updateChart(i) {
            var d = data[i];
            chart.setData(d);
            toggles.classed('toggled', function () {
                return (d3.select(this).attr('data-type') === d.type);
            });
            return d;
        }

        toggles.on('click', function (d, i) {
            clearTimeout(rotateTimer);
            updateChart(i);
        });

        function rotateChart() {
            i += 1;
            i = (i >= order.length) ? 0 : i;
            var d = updateChart(order[i]);
            rotateTimer = setTimeout(rotateChart, t);
        }

        rotateTimer = setTimeout(rotateChart, t);
    }());


    //陈立萍 add
    //easypiechart-data.js

    $(function () {
        $('#easypiechart-teal').easyPieChart({
            scaleColor: false,
            barColor: '#1ebfae'
        });
    });

    $(function () {
        $('#easypiechart-orange').easyPieChart({
            scaleColor: false,
            barColor: '#ffb53e'
        });
    });

    $(function () {
        $('#easypiechart-red').easyPieChart({
            scaleColor: false,
            barColor: '#f9243f'
        });
    });

    $(function () {
        $('#easypiechart-blue').easyPieChart({
            scaleColor: false,
            barColor: '#30a5ff'
        });
    });


    $(function () {
        var date = "";
        $.ajax({
            url: '/qjiang/v1/actors/active/machinepeople?date=' + date,
            type: 'GET',
            datatype: 'json',
            contentType: 'application/json;charset=utf-8',
            Accept: 'application/json',
            cache: false,
            success: function (data, textStatus, jqXHR) {
                $("#user_count").html(data.data[0].user_count);
                $("#machine_count").html(data.data[0].machine_count);
                $("#active_user_count").html(data.data[0].active_user_count);
                $("#active_machine_count").html(data.data[0].active_machine_count);

            },
            error: function (jqXHR, textStatus, errorThrown) {
                $('#result').text(errorThrown);
            }
        });
    })


    //easypiechart-data.js


    /* ---------- Sparkline Charts ---------- */
    //generate random number for charts

    $(function () {


        randNum = function () {
            //return Math.floor(Math.random()*101);
            return (Math.floor(Math.random() * (1 + 40 - 20)) ) + 20;
        }

        var chartColours = ['#2FABE9', '#FA5833', '#b9e672', '#bbdce3', '#9a3b1b', '#5a8022', '#2c7282'];

        //sparklines (making loop with random data for all 7 sparkline)
        i = 1;
        for (i = 1; i < 10; i++) {
            var data = [[1, 3 + randNum()], [2, 5 + randNum()], [3, 8 + randNum()], [4, 11 + randNum()], [5, 14 + randNum()], [6, 17 + randNum()], [7, 20 + randNum()], [8, 15 + randNum()], [9, 18 + randNum()], [10, 22 + randNum()]];
            placeholder = '.sparkLineStats' + i;

            if (retina()) {

                $(placeholder).sparkline(data, {
                    width: 200,//Width of the chart - Defaults to 'auto' - May be any valid css width - 1.5em, 20px, etc (using a number without a unit specifier won't do what you want) - This option does nothing for bar and tristate chars (see barWidth)
                    height: 60,//Height of the chart - Defaults to 'auto' (line height of the containing tag)
                    lineColor: '#2FABE9',//Used by line and discrete charts to specify the colour of the line drawn as a CSS values string
                    fillColor: '#f2f7f9',//Specify the colour used to fill the area under the graph as a CSS value. Set to false to disable fill
                    spotColor: '#467e8c',//The CSS colour of the final value marker. Set to false or an empty string to hide it
                    maxSpotColor: '#b9e672',//The CSS colour of the marker displayed for the maximum value. Set to false or an empty string to hide it
                    minSpotColor: '#FA5833',//The CSS colour of the marker displayed for the mimum value. Set to false or an empty string to hide it
                    spotRadius: 2,//Radius of all spot markers, In pixels (default: 1.5) - Integer
                    lineWidth: 1//In pixels (default: 1) - Integer
                });

                //only firefox sux in this case
                if (jQuery.browser.mozilla) {
                    $(placeholder).css('MozTransform', 'scale(0.5,0.5)').css('margin-top', '-10px');
                    $(placeholder).css('height', '30px').css('width', '100px').css('margin-left', '-20px').css('margin-right', '40px');
                } else {
                    $(placeholder).css('zoom', 0.5);
                }

            } else {

                $(placeholder).sparkline(data, {
                    width: 100,//Width of the chart - Defaults to 'auto' - May be any valid css width - 1.5em, 20px, etc (using a number without a unit specifier won't do what you want) - This option does nothing for bar and tristate chars (see barWidth)
                    height: 30,//Height of the chart - Defaults to 'auto' (line height of the containing tag)
                    lineColor: '#2FABE9',//Used by line and discrete charts to specify the colour of the line drawn as a CSS values string
                    fillColor: '#f2f7f9',//Specify the colour used to fill the area under the graph as a CSS value. Set to false to disable fill
                    spotColor: '#467e8c',//The CSS colour of the final value marker. Set to false or an empty string to hide it
                    maxSpotColor: '#b9e672',//The CSS colour of the marker displayed for the maximum value. Set to false or an empty string to hide it
                    minSpotColor: '#FA5833',//The CSS colour of the marker displayed for the mimum value. Set to false or an empty string to hide it
                    spotRadius: 2,//Radius of all spot markers, In pixels (default: 1.5) - Integer
                    lineWidth: 1//In pixels (default: 1) - Integer
                });

            }

        }

        /* ---------- Init jQuery Knob - disbaled in IE8, IE7, IE6 ---------- */
        if (jQuery.browser.version.substring(0, 2) == "8.") {

            //disable jQuery Knob

        } else {

            $('.circleChart').each(function () {

                var circleColor = $(this).parent().css('color');

                $(this).knob({
                    'min': 0,
                    'max': 100,
                    'readOnly': true,
                    'width': 120,
                    'height': 120,
                    'fgColor': circleColor,
                    'dynamicDraw': true,
                    'thickness': 0.2,
                    'tickColorizeValues': true,
                    'skin': 'tron'
                });

            });

        }

        /*------- Just Gage Init -------*/
        /*
        g1 = new JustGage({id: "g1", value: 67, min: 0, max: 100, title: "Visitors", label: "per minute"});

        g1a = new JustGage({id: "g1a", value: 45, min: 0, max: 100, title: "Errors", label: "average"});
        g2 = new JustGage({id: "g2", value: 15, min: 0, max: 100, title: "Timers", label: ""});
        g2a = new JustGage({id: "g2a", value: 7, min: 0, max: 100, title: "Alerts", label: ""});
        g2b = new JustGage({id: "g2b", value: 22, min: 0, max: 100, title: "Events", label: ""});

        setInterval(function () {
                g1.refresh(getRandomInt(50, 100));
                g1a.refresh(getRandomInt(50, 100));
                g2.refresh(getRandomInt(0, 50));
                g2a.refresh(getRandomInt(0, 50));
                g2b.refresh(getRandomInt(0, 50))
            }, 2000
        );
         */
        /*------- Easy Pie Chart Init -------*/
        $('.percentage').easyPieChart();
        $('.percentage-light').easyPieChart();

        $('.updateEasyPieChart').on('click', function (e) {
            e.preventDefault();
            $('.percentage, .percentage-light').each(function () {
                $(this).data('easyPieChart').update(Math.round(100 * Math.random()));
            });
        });
    })

    //clp add


    /*------- Gauge -------*/
    var opts = {
        lines: 11, // The number of lines to draw
        angle: 0.03, // The length of each line
        lineWidth: 0.43, // The line thickness
        pointer: {
            length: 0.74, // The radius of the inner circle
            strokeWidth: 0.034, // The rotation offset
            color: '#484848' // Fill color
        },
        limitMax: 'false',   // If true, the pointer will not go past the end of the gauge
        colorStart: '#f4b162',   // Colors
        colorStop: '#f4b162',    // just experiment with them
        strokeColor: '#f5f5f5',   // to see which ones work best for you
        generateGradient: true
    };
    var target = document.getElementById('gauge1'); // your canvas element
    var gauge = new Gauge(target).setOptions(opts); // create sexy gauge!
    gauge.maxValue = 2000; // set max gauge value
    gauge.animationSpeed = 40; // set animation speed (32 is default value)
    gauge.set(1000); // set actual value

    var opts2 = {
        lines: 11, // The number of lines to draw
        angle: 0.03, // The length of each line
        lineWidth: 0.43, // The line thickness
        pointer: {
            length: 0.74, // The radius of the inner circle
            strokeWidth: 0.034, // The rotation offset
            color: '#484848' // Fill color
        },
        limitMax: 'false',   // If true, the pointer will not go past the end of the gauge
        colorStart: '#71d398',   // Colors
        colorStop: '#71d398',    // just experiment with them
        strokeColor: '#f5f5f5',   // to see which ones work best for you
        generateGradient: true
    };
    var target = document.getElementById('gauge2'); // your canvas element
    var gauge = new Gauge(target).setOptions(opts2); // create sexy gauge!
    gauge.maxValue = 2000; // set max gauge value
    gauge.animationSpeed = 80; // set animation speed (32 is default value)
    gauge.set(1500); // set actual value

});

function getRandomData1() {
    // var data = [];
    // if (data.length > 0)
    //     data = data.slice(1);
    //
    // // do a random walk
    // while (data.length < 300) {
    //     var prev = data.length > 0 ? data[data.length - 1] : 50;
    //     var y = prev + Math.random() * 10 - 5;
    //     if (y < 0)
    //         y = 0;
    //     if (y > 100)
    //         y = 100;
    //     data.push(y);
    // }

    // zip the generated y values with the x values
    var res = [];
    for (var i = 0; i < 300; ++i)
        res.push([i, 0])
    return res;
}

//
function createPlot() {
    var plot = new Object();
    if ($("#realtime-update")) {
        var options = {
            series: {shadowSize: 1},
            lines: {fill: true, fillColor: {colors: [{opacity: 1}, {opacity: 0.1}]}},
            yaxis: {min: 0, max: 100},
            xaxis: {show: false},
            colors: ["#57889c"],
            grid: {
                tickColor: "#dddddd",
                borderWidth: 0
            },
        };
        plot = $.plot($("#realtime-update"), [getRandomData1()], options);
    }
    console.log(plot);
    return plot;
}

//
function openSocket() {
    var websocket = new Object();

    var path = window.location.host;
    if ('WebSocket' in window) {
        websocket = new WebSocket("ws://" + path + "/qjiang/v1/wsocket");
        console.log("WebSocket in window");
    } else if ('MozWebSocket' in window) {
        websocket = new MozWebSocket("ws://" + path + "/qjiang/v1/wsocket");
        console.log("WebSocket in MozWebSocket");
    } else {
        websocket = new SockJS("http://" + path + "/qjiang/v1/wsocket/sockjs");
        console.log("WebSocket in SockJS");
    }
    //console.log(websocket);
    websocket.onopen = function (event) {
        console.log("WebSocket:已连接");
    };

    websocket.onmessage = function (event) {
        console.log("WebSocket:收到一条消息-norm", event);
        reflush(myPlot, event);
    };

    websocket.onerror = function (event) {
        console.log("WebSocket:发生错误 ");
        console.log(event);
        alert("WebSocket:发生错误 "+event.toString());
    };

    websocket.onclose = function (event) {
        console.log("WebSocket:已关闭");
        console.log(event);
        alert("WebSocket:已关闭");
    };

    return websocket;
}


function reflush(plot, event) {
    var data = JSON.parse(event.data);
    if(plot!=null && data.length>0) {
        var res = [];
        res.length = 0;
        for (var i = 0; i < data.length; ++i) {
            res.push([i, parseInt(data[i].propvalue)]);
        }
        plot.setData([res]);
        // since the axes don't change, we don't need to call plot.setupGrid()
        plot.draw();
    }else{
        console.log("plot is not found!");
    }
}